//
//  LYEQRCodeViewController.m
//  artist
//
//  Created by Jay_Apple on 16/5/12.
//  Copyright © 2016年 viviyoo. All rights reserved.
//

#import "LYEQRCodeViewController.h"
#import <AVFoundation/AVFoundation.h>

@interface LYEQRCodeViewController ()<AVCaptureMetadataOutputObjectsDelegate>


@property (weak, nonatomic) AVCaptureSession *session;
@property (weak, nonatomic) AVCaptureVideoPreviewLayer *layer;

@end

@implementation LYEQRCodeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self startScanning];
}


- (void)startScanning{



    // 1.获取捕捉会话
    AVCaptureSession *session = [[AVCaptureSession alloc] init];
    self.session = session;
    
    // 2.设置捕捉会话的输入设备
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];
    [session addInput:input];
    
    // 3.设置捕捉花卉的输出设备
    AVCaptureMetadataOutput *output = [[AVCaptureMetadataOutput alloc] init];
    [output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    [output setRectOfInterest:CGRectMake((LYScreenHeight - 250)*0.5 / LYScreenHeight, (LYScreenWidth - 250)*0.5/LYScreenWidth, 250/LYScreenHeight,250/LYScreenWidth)];
    [session addOutput:output];
    [output setMetadataObjectTypes:@[AVMetadataObjectTypeQRCode]];
    
    // 4.添加扫描阅览的layer
    AVCaptureVideoPreviewLayer *player = [[AVCaptureVideoPreviewLayer alloc] initWithSession:session];
    player.frame = CGRectMake(0, 0, LYScreenWidth, LYScreenHeight);
    self.layer = player;
    [self.view.layer insertSublayer:player atIndex:0];
    
    // 5.开始扫描
    [session startRunning];

}



#pragma mark - 实现元数据的回调方法
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
    if (metadataObjects.count > 0) {
        AVMetadataMachineReadableCodeObject *object = [metadataObjects lastObject];
        
        [self.session stopRunning];
        [self.layer removeFromSuperlayer];
        
        NSArray *component = [object.stringValue componentsSeparatedByString:@"#"];
        
        NSString *vertify = component[0];
        NSString *order_sn = component[1];
        
        
        [MBProgressHUD showMessage:nil];
        [LYRequestTool scanVerifyWithToken:LYToken order_sn:order_sn verify_code:vertify success:^(NSString *msg) {
            [MBProgressHUD hideHUD];
            [MBProgressHUD showSuccess:msg];
            
        } failure:^(NSString *code, NSString *message) {
            [MBProgressHUD hideHUD];
            [MBProgressHUD showError:message];
        }];
        
        [self.navigationController popViewControllerAnimated:YES];
    }
}



@end
